package com.tuanzi.loan.web.bean.application;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.application.LoanApplicationExportGroup;
import com.tuanzi.loan.business.entity.application.LoanApplicationExportGroupPage;
import com.tuanzi.loan.business.service.application.LoanApplicationExportGroupService;
import com.tuanzi.loan.business.service.application.LoanApplicationExportGroupPageService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.EXPORT_TYPE;

/**
 * @Auther: hequnayu
 * @Date: 2019/7/30 16:47
 * @Description:
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanApplicationExportGroupInfoBean extends JSFInfoBean<LoanApplicationExportGroup> {
    private static final long serialVersionUID = 3619020544105447333L;

    @Autowired
    private LoanApplicationExportGroupPageService bannerPageService;
    @Autowired
    private LoanApplicationExportGroupService groupService;
    private List<LoanApplicationExportGroupPage> pageList;

    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");
        pageList = bannerPageService.findAll();
        if (StringUtils.isNotBlank(id)) {
            $ = groupService.findOne(NumberUtils.toLong(id));
        } else {
            $ = new LoanApplicationExportGroup();
            Integer biggestGroupId = groupService.getBiggestGroupId();
            $.setGroupId(biggestGroupId);
            changeStatusToAdd();
        }
    }

    public void onSave() {
        if(null == $.getPageId()) {
            addFiledMessage("作用页面名称不能为空");
            return;
        }
        if(StringUtils.isEmpty($.getName())) {
            addFiledMessage("名称不能为空");
            return;
        }
        if(null == $.getGroupId()) {
            addFiledMessage("分组ID不能为空");
            return;
        }
        if(null ==$.getType()) {
            addFiledMessage("类型不能为空");
            return;
        }
        if ($.getId() == null){
            LoanApplicationExportGroup exportGroup = groupService.findByGroupIdAndType($.getGroupId(),$.getType());
            if (exportGroup != null){
                addFiledMessage("相同类型下分组ID不能重复");
                return;
            }
        }
        $ = groupService.saveOrUpdate($);
        changeStatusToView();
        addSuccessfullyMessage();
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(EXPORT_TYPE);
    }
}
